package com.example.fruitdemo.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.fruitdemo.mapper.UserMapper;
import com.example.fruitdemo.pojo.User;
import com.example.fruitdemo.ruslet.R;
import com.example.fruitdemo.service.UserService;
import com.example.fruitdemo.util.Code;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.Duration;
import java.time.format.DateTimeFormatter;
import java.util.Random;
import java.util.UUID;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
 @Autowired
 private StringRedisTemplate redisTemplate;
 @Autowired
 private UserMapper userMapper;
 @Autowired
 private UserService userService;
    @Override
    public R<String> login(User user, HttpServletResponse response) throws IOException {
        String username=user.getUsername();
        String pwd=user.getPassword();
        //1.先去数据库查询用户名
        LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername,username);
        User one = this.getOne(queryWrapper);
        System.out.println(one);
        String userid=one.getId().toString();
        if(one!=null){
            //如果不为空，再判断密码
            if(one.getPassword().equals(pwd))
            {
                //密码正确，放行,设置token放入redis
                //1.存用户id为key,uuid为值
                saveToRedis(response,one, userid);
                //response.setHeader("Authorization",uuid);
               //response.setHeader("Access-Control-Allow-Headers","Authorization");
               // response.sendRedirect("index.html");
                return R.Ok();
            }else{
                return R.Err("密码错误！");
            }
        }else return R.Err("用户名不存在！");
    }

    private void saveToRedis (HttpServletResponse response,User one, String userid) {
        String uuid = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set("user:"+ userid,uuid);
        //2.以uuid为key,用户信息为值存入
        redisTemplate.opsForValue().set(uuid,JSON.toJSONString(one));
        //给前端设置头信息
        response.setHeader("Authorization",uuid);
    }

    @Override
    public R<String> loginout(String authorization) {
        //String authroization = request.getHeader("Authroization");
        //查询redis,若存在，删除所有用户信息
        if( redisTemplate.opsForValue().get(authorization)!=null)
        {
            String json = redisTemplate.opsForValue().get(authorization);
           // System.out.println(json);
            User user = JSONObject.parseObject(json,User.class);

            Long id = user.getId();
            redisTemplate.delete("user:"+id.toString());
            redisTemplate.delete(authorization);
        }
        return R.Ok();
    }

    @Override
    public R<Object> register(User user,HttpServletResponse response) {
        //先判断用户名是否存在

        String username = user.getUsername();
        LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername,username);

        if(getOne(queryWrapper)==null){
            //创建用户
             User user1=new User();
             user1.setUsername(user.getUsername());
             user1.setPassword(user.getPassword());
             user1.setEmail(user.getEmail());
            int count = userMapper.insert(user1);
            System.out.println(user1);
            if(count>0){
                //给redis储存信息,给前端设置响应头
                saveToRedis(response,user1,user1.getId().toString());
                //返回正确
                return R.Ok();
            } else {
                return R.Err("错误");
            }
        }else{
            //用户名已经存在，给一个重复提醒
            R<Object> r=new R<>();
            r.setCode(Code.USERNAME_EXITS_CODE);
            r.setMsg("用户名已经存在");
            return r;
        }
    }

    @Override
    public R<Object> resetpwd(User user, HttpServletResponse response) {
        String username = user.getUsername();
        LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername,username);

        if(getOne(queryWrapper)==null) {
            //用户不存在,返回错误信息
            return R.Err("用户不存在！");
        }else {
            //存在，判断邮箱是否正确
            User one = getOne(queryWrapper);
            if (one.getEmail() .equals(user.getEmail())) {
                //邮箱正确，可以修改密码
                one.setPassword(user.getPassword());
                //提交修改
                boolean flag = userService.updateById(one);
                if (flag) {
                    //修改redis储存信息,给前端设置响应头
                    saveToRedis(response,one,one.getId().toString());
                    //返回正确
                    return R.Ok("修改成功！新密码为："+user.getPassword()+" 请牢记！");
                } else return R.Err("修改失败!");

            }else {
                //邮箱不正确,无法找密码
                return R.Err("邮箱不正确！本项目当前仅支持邮箱找回，请联系作者找回：qq:1046407954");
            }
        }
    }

    //返回用户信息
    @Override
    public R<User> getUser(String authorization) {
        String s = redisTemplate.opsForValue().get(authorization);
        User user = JSONObject.parseObject(s, User.class);
        return R.Ok(user);
    }
    //根据authorization查询id
    @Override
    public Long getidByAuth(String authorization) {
        String s = redisTemplate.opsForValue().get(authorization);
        User user = JSONObject.parseObject(s, User.class);
        return user.getId();
    }

    @Override
    public R<Object> setuser(User user) {
        User one = this.getById(user.getId());
        //设置值
        one.setUsername(user.getUsername());
        one.setEmail(user.getEmail());
        one.setPhone(user.getPhone());
        one.setAddress(user.getAddress());
        boolean b = this.updateById(one);
        if(b){
            //修改成功！返回
            //继续修改redis中的数据
            String authorization = redisTemplate.opsForValue().get(Code.USER + one.getId());
            redisTemplate.opsForValue().set(authorization,JSON.toJSONString(one));
            return R.Ok(one,"修改成功");
        }else{
            return R.Err("修改失败");
        }
    }


}
